package cn.hsa.fqz.util;


import cn.hsa.fqz.task.service.dto.TreeDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TreeUtil {


  /**
   * 根节点
   */
  private TreeDTO root;
  /**
   * 所有集合
   */
  private List<TreeDTO> list;

  public TreeUtil(TreeDTO root, List<TreeDTO> list) {
    this.root = root;
    this.list = list;
  }

  public synchronized TreeDTO build() {
    if(list == null || list.size() == 0){
      return root;
    }
    List<? extends TreeDTO> parentList = list.stream().filter(l ->
        l.getPid() == null || l.getPid().equals(root.getId()))
        .collect(Collectors.toList());
    list.removeAll(parentList);
    convert(parentList, list);
    root.getChildren().addAll(parentList);
    return root;
  }

  /**
   * 转换递归
   *
   * @param parentList
   * @param nodeList
   */
  private synchronized void convert(List<? extends TreeDTO> parentList, List<? extends TreeDTO> nodeList) {
    List<TreeDTO> tempParentList = new ArrayList<>();
    List<TreeDTO> tempNodeList = new ArrayList<>();
    parentList.forEach(parent -> {
      nodeList.forEach(
          node -> {
            if (node.getPid().equals(parent.getId())) {
              parent.getChildren().add(node);
              tempNodeList.add(node);
              tempParentList.add(node);
            }
          }
      );
    });
    nodeList.removeAll(tempNodeList);
    if (!nodeList.isEmpty()) {
      convert(tempParentList, nodeList);
    }
  }
}
